// lib/pages/ozone_page.dart
import 'dart:async';
import 'dart:math' as math;

import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../controllers/device_manager_controller.dart';
import '../widgets/common_bottom_nav.dart';

class OzonePage extends StatefulWidget {
  const OzonePage({Key? key}) : super(key: key);

  @override
  State<OzonePage> createState() => _OzonePageState();
}

class _OzonePageState extends State<OzonePage> {
  final dm = Get.find<DeviceManagerController>();

  Timer? _timer;

  // 本地运行进度（0~1）
  double progress = 0;

  // 模式总时长（秒）：标准/强力
  int totalSeconds = 30;

  // 剩余秒数
  int remainSeconds = 30;

  // 历史记录（后续可换 Hive）
  final List<OzoneRecord> records = [];

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  //========================================
  // 安全提示对话框（开启前必须确认）
  //========================================
  Future<bool> _showSafetyDialog() async {
    return await showDialog<bool>(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text("安全提示"),
          content: const Text(
            "臭氧对人体有刺激性，请确认室内无人后再继续。\n\n是否确认开启臭氧消毒？",
            style: TextStyle(fontSize: 15),
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context, false),
              child: const Text("取消"),
            ),
            ElevatedButton(
              onPressed: () => Navigator.pop(context, true),
              child: const Text("确认开启"),
            ),
          ],
        );
      },
    ) ??
        false;
  }

  //========================================
  // 点击“开始消毒” → 先弹提示再启动
  //========================================
  void _onStartPressed() async {
    final ok = await _showSafetyDialog();
    if (!ok) return;

    _startOzone();
  }

  //========================================
  // 真正开始臭氧消毒
  //========================================
  void _startOzone() {
    if (dm.ozone.isFalse) dm.toggleOzone();

    remainSeconds = totalSeconds;
    progress = 0;

    _timer?.cancel();
    _timer = Timer.periodic(const Duration(seconds: 1), (t) {
      setState(() {
        remainSeconds--;
        progress = 1 - remainSeconds / totalSeconds;

        if (remainSeconds <= 0) {
          t.cancel();
          if (dm.ozone.isTrue) dm.toggleOzone();

          // 写入历史记录
          records.insert(
            0,
            OzoneRecord(
              DateTime.now(),
              totalSeconds,
              totalSeconds == 30 ? "标准模式" : "强力模式",
            ),
          );
        }
      });
    });
  }

  void _stopOzone() {
    if (dm.ozone.isTrue) dm.toggleOzone();
    _timer?.cancel();

    setState(() {
      progress = 0;
      remainSeconds = totalSeconds;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF7F8FA),

      body: Column(
        children: [
          _buildCustomHeader(),  // 顶部自定义工具条

          Expanded(
            child: SingleChildScrollView(
              padding: const EdgeInsets.all(20),
              child: Column(
                children: [
                  const SizedBox(height: 10),
                  _buildBigProgressDial(),
                  const SizedBox(height: 20),
                  _buildInfoCards(),
                  const SizedBox(height: 20),
                  _buildModeSelector(),
                  const SizedBox(height: 20),
                  _buildStartStopButton(),
                  const SizedBox(height: 25),
                  _buildHistoryList(),
                ],
              ),
            ),
          ),
        ],
      ),

      bottomNavigationBar: const CommonBottomNav(),
    );
  }




  // ============================
// 顶部自定义标题栏（符合设计稿）
// ============================
  Widget _buildCustomHeader() {
    return SafeArea(
      bottom: false,  // 只占用顶部的安全区
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        color: Colors.white,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            // 左侧 返回 + 标题
            Row(
              children: [
                GestureDetector(
                  onTap: () => Get.back(),
                  child: const Icon(Icons.arrow_back, color: Colors.black87, size: 24),
                ),
                const SizedBox(width: 12),
                const Text(
                  "臭氧",
                  style: TextStyle(fontSize: 20, fontWeight: FontWeight.w600),
                ),
              ],
            ),

            // 右侧 ON/OFF
            Obx(() {
              final on = dm.ozone.value;
              return GestureDetector(
                onTap: () => dm.toggleOzone(),
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 6),
                  decoration: BoxDecoration(
                    color: on ? Colors.blueAccent : Colors.grey.shade300,
                    borderRadius: BorderRadius.circular(20),
                  ),
                  child: Text(
                    on ? "ON" : "OFF",
                    style: TextStyle(
                      color: on ? Colors.white : Colors.black87,
                      fontSize: 14,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ),
              );
            }),
          ],
        ),
      ),
    );
  }



  //========================================
  // 顶部 ON/OFF 开关
  //========================================
  Widget _buildHeaderSwitch() {
    return Obx(() {
      final on = dm.ozone.value;

      return Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          GestureDetector(
            onTap: () => dm.toggleOzone(),
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 6),
              decoration: BoxDecoration(
                color: on ? Colors.blueAccent : Colors.grey.shade300,
                borderRadius: BorderRadius.circular(18),
              ),
              child: Text(
                on ? "ON" : "OFF",
                style: TextStyle(
                  color: on ? Colors.white : Colors.black87,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
          ),
        ],
      );
    });
  }

  //========================================
  // 大号进度环（设计稿风格）
  //========================================
  Widget _buildBigProgressDial() {
    return SizedBox(
      width: 230,
      height: 230,
      child: Stack(
        alignment: Alignment.center,
        children: [
          // 背景浅色圆
          Container(
            width: 230,
            height: 230,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              color: Colors.white,
              boxShadow: [
                BoxShadow(
                  color: Colors.blue.shade50,
                  blurRadius: 20,
                )
              ],
            ),
          ),

          CustomPaint(
            size: const Size(200, 200),
            painter: _ProgressArcPainter(progress),
          ),

          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                dm.ozone.value ? "消毒中" : "未运行",
                style: const TextStyle(
                    color: Colors.blueAccent,
                    fontSize: 18,
                    fontWeight: FontWeight.w500),
              ),
              const SizedBox(height: 6),
              Text(
                "${(progress * 100).toStringAsFixed(0)}%",
                style: const TextStyle(
                    color: Colors.blueAccent,
                    fontSize: 32,
                    fontWeight: FontWeight.bold),
              ),
            ],
          ),
        ],
      ),
    );
  }

  //========================================
  // 信息卡片：臭氧浓度 / 时间 / 进度
  //========================================
  Widget _infoCard(String icon, String title, String value) {
    return Container(
      width: 100,
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border.all(color: Colors.blue.shade50),
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.blue.shade50,
            blurRadius: 8,
          )
        ],
      ),
      child: Column(
        children: [
          Text(icon, style: const TextStyle(fontSize: 24)),
          const SizedBox(height: 6),
          Text(title,
              style: const TextStyle(fontSize: 12, color: Colors.black54)),
          const SizedBox(height: 6),
          Text(value,
              style: const TextStyle(
                  fontSize: 15,
                  color: Colors.black87,
                  fontWeight: FontWeight.w600)),
        ],
      ),
    );
  }

  Widget _buildInfoCards() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        _infoCard("🧪", "臭氧浓度", "0.3mg/㎥"),
        _infoCard("⏱", "消毒时间",
            totalSeconds == 30 ? "30秒" : "${totalSeconds ~/ 60}分钟"),
        _infoCard("⏳", "运行进度", "${(progress * 100).toInt()}%"),
      ],
    );
  }

  //========================================
  // 模式选择
  //========================================
  Widget _buildModeSelector() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        _modeButton("标准模式", 30),
        const SizedBox(width: 12),
        _modeButton("强力模式", 15 * 60),
      ],
    );
  }

  Widget _modeButton(String label, int seconds) {
    final active = totalSeconds == seconds;

    return GestureDetector(
      onTap: () {
        setState(() {
          totalSeconds = seconds;
          remainSeconds = seconds;
          progress = 0;
        });
      },
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 200),
        padding: const EdgeInsets.symmetric(horizontal: 26, vertical: 12),
        decoration: BoxDecoration(
          color: active ? Colors.blueAccent : Colors.grey.shade300,
          borderRadius: BorderRadius.circular(22),
          boxShadow: active
              ? [
            BoxShadow(
              color: Colors.blue.shade200,
              blurRadius: 6,
            )
          ]
              : null,
        ),
        child: Text(
          label,
          style: TextStyle(
            fontSize: 15,
            color: active ? Colors.white : Colors.black87,
          ),
        ),
      ),
    );
  }

  //========================================
  // “开始消毒 / 停止消毒” 按钮
  //========================================
  Widget _buildStartStopButton() {
    return GestureDetector(
      onTap: dm.ozone.value ? _stopOzone : _onStartPressed,
      child: Container(
        width: double.infinity,
        padding: const EdgeInsets.symmetric(vertical: 16),
        decoration: BoxDecoration(
          color: dm.ozone.value ? Colors.redAccent : Colors.blueAccent,
          borderRadius: BorderRadius.circular(26),
          boxShadow: [
            BoxShadow(
              color: Colors.black12,
              blurRadius: 8,
            )
          ],
        ),
        alignment: Alignment.center,
        child: Text(
          dm.ozone.value ? "停止消毒" : "开始消毒",
          style: const TextStyle(fontSize: 18, color: Colors.white),
        ),
      ),
    );
  }

  //========================================
  // 历史记录
  //========================================
  Widget _buildHistoryList() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
      ),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              const Text("消毒记录",
                  style: TextStyle(fontSize: 14, color: Colors.black87)),
              GestureDetector(
                onTap: () => setState(() => records.clear()),
                child: const Text("清除全部",
                    style: TextStyle(
                        fontSize: 13,
                        color: Colors.blueAccent,
                        decoration: TextDecoration.underline)),
              ),
            ],
          ),
          const SizedBox(height: 12),
          ...records.map((r) => _recordTile(r)).toList(),
        ],
      ),
    );
  }

  Widget _recordTile(OzoneRecord r) {
    return Container(
      margin: const EdgeInsets.only(bottom: 10),
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
      decoration: BoxDecoration(
        color: Colors.grey.shade50,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text("${r.time.year}-${r.time.month}-${r.time.day} "
              "${r.time.hour}:${r.time.minute}",
              style: const TextStyle(color: Colors.black87, fontSize: 13)),
          Text(r.mode, style: const TextStyle(color: Colors.black54)),
          Text("${r.seconds}秒",
              style: const TextStyle(color: Colors.black87, fontSize: 13)),
        ],
      ),
    );
  }
}

//========================================
// 数据模型
//========================================
class OzoneRecord {
  final DateTime time;
  final int seconds;
  final String mode;

  OzoneRecord(this.time, this.seconds, this.mode);
}

//========================================
// 进度圆环 painter
//========================================
class _ProgressArcPainter extends CustomPainter {
  final double progress;

  _ProgressArcPainter(this.progress);

  @override
  void paint(Canvas canvas, Size size) {
    final center = size.center(Offset.zero);
    final radius = size.width / 2 - 16;

    final basePaint = Paint()
      ..style = PaintingStyle.stroke
      ..strokeWidth = 16
      ..color = Colors.blue.shade100
      ..strokeCap = StrokeCap.round;

    final progressPaint = Paint()
      ..style = PaintingStyle.stroke
      ..strokeWidth = 18
      ..strokeCap = StrokeCap.round
      ..shader = SweepGradient(
        colors: const [
          Color(0xFF64B5F6),
          Color(0xFF2196F3),
          Color(0xFF1976D2),
        ],
      ).createShader(Rect.fromCircle(center: center, radius: radius));

    // 背景弧
    canvas.drawArc(
      Rect.fromCircle(center: center, radius: radius),
      math.pi * 1.2,
      math.pi * 1.6,
      false,
      basePaint,
    );

    // 进度弧
    canvas.drawArc(
      Rect.fromCircle(center: center, radius: radius),
      math.pi * 1.2,
      math.pi * 1.6 * progress,
      false,
      progressPaint,
    );
  }

  @override
  bool shouldRepaint(covariant _ProgressArcPainter oldDelegate) {
    return progress != oldDelegate.progress;
  }
}
